
# 更新鸭力的数值和恢复时间
import datetime
import time

from duckserver.models import User


def refreshPower(userid):
    # 单独对鸭力进行处理
    user = User.objects.get(userid=userid)
    remain_power = user.power
    recover_time = user.recoverTime
    now = datetime.datetime.now()
    (now - recover_time)
    st = int(time.mktime(now.timetuple()) - time.mktime(recover_time.timetuple()))
    remain_power += st / 1800
    if remain_power >= 100:
        user.power = 100
    else:
        user.power = remain_power
    user.recoverTime = now
    user.save()


def getPower(userid, num):
    refreshPower(userid)
    user = User.objects.get(userid=userid)
    remain_power = user.power
    remain_power += num
    if remain_power >= 100:
        user.power = 100
    else:
        user.power = remain_power
    user.save()


def costPower(userid, num):
    refreshPower(userid)
    user = User.objects.get(userid=userid)
    remain_power = user.power
    if remain_power >= num:
        user.power = remain_power - num
        user.save()
        return True
    else:
        return False


def getEgg(userid, num):
    user = User.objects.get(userid=userid)
    user.credit+= num
    user.save()


def costEgg(userid, num):
    user = User.objects.get(userid=userid)
    remain_egg = user.credit
    if remain_egg >= num:
        user.credit = remain_egg - num
        user.save()
        return True
    else:
        return False
